package com.uto;

import com.uto.backend.interfaces.IAppManager;
import com.uto.backend.interfaces.IServerResponse;
import com.uto.frontend.interfaces.IServiceListener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class NewGame extends Activity implements OnClickListener {

	private final String TAG = "com.uto.NewGame";
	
	private final int IS_OK = 0;
	private final int NOT_OK = 1;
	
	private User user;
	
	EditText numOfPlayers;
	EditText startMoney;
	Spinner regionSpinner;
	
	//A progress dialog for when waiting for background work
	private ProgressDialog pd;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_game);

		user = getIntent().getParcelableExtra("user");
		
		// Set up click listener for register button
		View newGameButton = this.findViewById(R.id.NewGameButton);
		newGameButton.setOnClickListener(this);
		numOfPlayers = (EditText)this.findViewById(R.id.NumOfPlayersEdit);
		startMoney = (EditText)this.findViewById(R.id.StartMoneyEdit);
		
	    regionSpinner = (Spinner) findViewById(R.id.region_manu);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.regions, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    regionSpinner.setAdapter(adapter);



	}

	public void onClick(View v) {
		boolean test1 = checkField(numOfPlayers);
		boolean test2 = checkField(startMoney);
		
		if (test1==false || test2==false)
			return;
		
		
		int numOfPlayersInt =  Integer.parseInt(numOfPlayers.getText().toString());
		int startMoneyInt =  Integer.parseInt(startMoney.getText().toString());
		user.setMoney(startMoneyInt);
		user.setStreets("");
		
		IAppManager manager = MyServiceConnection.getAppManager();
		if (manager==null){
			Log.v(TAG, "IAppManager is null");
			Toast.makeText(NewGame.this, getString(R.string.start_game_fail), Toast.LENGTH_LONG).show();
			return;
		}
		
		try {
			if (user == null)
				Log.d(TAG,"user is null");
			String userName =  user.getUsername();
			Log.d(TAG,"user name is: "+userName);
			manager.startNewGame(listener, numOfPlayersInt, startMoneyInt,userName);
		} catch (RemoteException e) {
			e.printStackTrace();
			Toast.makeText(NewGame.this, getString(R.string.start_game_fail), Toast.LENGTH_LONG).show();
			return;
		}
		pd = ProgressDialog.show(NewGame.this, getString(R.string.starting_game),"");
				
	}
	
	private boolean checkField(EditText field){
		if (field==null || field.getText()==null || field.getText().toString().trim().length()==0){
			field.setError(getString(R.string.can_not_be_empty));
			return false;
		}
		return true;
	}

	private String returnRegion() {
		int region;
		region = regionSpinner.getSelectedItemPosition();
		return getResources().getStringArray(R.array.regions)[region];
	}
	
	private final IServiceListener.Stub listener = new IServiceListener.Stub(){

		public void handleMessage(IServerResponse response) {
			Message msg = new Message();
			try {
				if (response == null)
				{
					msg.arg1 = NOT_OK;
					handler.sendMessage(msg);
					Log.e(TAG, "null response");
				}

				else if (!response.isOk())
				{
					msg.arg1 = NOT_OK;
					msg.obj = response.getMessage();
					handler.sendMessage(msg);
				}
				else{
					msg.arg1 = IS_OK;
					handler.sendMessage(msg);					
				}
			} catch (Exception e) {
				msg.arg1 = NOT_OK;
				handler.sendMessage(msg);
				e.printStackTrace();
			}
		}
	};
	
	private Handler handler = new Handler(){
		public void handleMessage(Message msg){
			if (pd!=null && pd.isShowing())
				pd.dismiss();

			if (msg.arg1==NOT_OK){
				String message = (String)msg.obj;
				if (message != null)
					Toast.makeText(NewGame.this, message, Toast.LENGTH_LONG).show();
				else
					Toast.makeText(NewGame.this, getString(R.string.start_game_fail), Toast.LENGTH_LONG).show();
			}
			else{
				
				Intent gameIntent = new Intent(NewGame.this, MapViewOpenStreet.class);
				gameIntent.putExtra("user" , user);			
				SharedPreferences settings = getSharedPreferences(UTO.USER_FILE, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.putBoolean("inGame", true);
				// Commit the edits!
				editor.commit();
				startActivity(gameIntent);
				
			}



		}
	};

}